using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using Weight.Base;

namespace Weight.Base
{
    public class XMLConfigManager<T> where T: BaseSetting
    {
        /// <summary>
        /// 配置文件路径
        /// </summary>
        private string mPath = string.Empty;

        /// <summary>
        /// 配置文件版本
        /// </summary>
        private int Version;

        public string ConfigPath
        {
            get
            {
                return mPath;
            }
        }

        /// <summary>
        /// 禁止无参构造
        /// </summary>
        private XMLConfigManager() { }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <param name="version">版本</param>
        public XMLConfigManager(string fileName,int version)
        {
            string dir = Environment.CurrentDirectory + @"\config\";
            mPath = dir + fileName;
            Version = version;
            //创建目录
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            //创建默认文档
            if(!File.Exists(mPath))
            {
                var entity= Activator.CreateInstance<T>();
                saveConfig(entity);
            }
        }
      

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <returns></returns>
        public   T readConfig()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(mPath);
            string content = doc.InnerXml;
            
            var entity =  XMLHelper.DESerialize<T> (content);
            Upgrade(entity);
            return entity;
        }



        /// <summary>
        /// 保存配置文件
        /// </summary>
        /// <returns></returns>
        public bool saveConfig(T entity)
        {
            try
            {
                string content = XMLHelper.Serialize<T>(entity);
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(content);
                doc.Save(mPath);
                return true;
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog( "保存配置文件异常", ex);
                return false;
            }
        }

        /// <summary>
        /// 升级配置文件
        /// </summary>
        /// <param name="entity">配置参数</param>
        /// <returns></returns>
        public bool Upgrade(T entity)
        {
            if (Version > entity.XmlVersion.VersionNO)
            {
                entity.setDefaultConfig();
                entity.XmlVersion.VersionNO = Version;
                saveConfig(entity);
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}


